/*
 * @Author: wangjq4214
 * @Date: 2022-05-03 22:42:37
 * @LastEditTime: 2022-05-04 14:43:59
 * @LastEditors: wangjq4214
 */
import {
  Form,
  Select,
  Button,
  InputNumber,
  FormInstance,
} from '@arco-design/web-react';
import { post } from '@/apis';
import { STORAGE_ADD_URL } from '@/apis/storage';
import { loadingAtom, stepAtom } from '../model';

const FormItem = Form.Item;
const Option = Select.Option;

const NewForm = () => {
  const formRef = useRef<FormInstance<{
    storageType: number;
    storageScale: number;
    mainNodeMemory: number;
    slaveNodeMemory: number;
  }> | null>();
  const [storageType, setStorageType] = useState(1);
  const setLoading = useSetAtom(loadingAtom);
  const setStep = useSetAtom(stepAtom);

  const handleStorageTypeChange = (e: number) => {
    setStorageType(e);
    formRef.current?.setFields({
      storageScale: { value: 1 },
      mainNodeMemory: { value: 128 },
      slaveNodeMemory: { value: 128 },
    });
  };

  const handleSubmit = () => {
    setLoading(true);
    const data = formRef.current?.getFieldsValue();

    post(STORAGE_ADD_URL, { ...data })
      .then(() => {
        setStep('submit');
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => setLoading(false));
  };

  return (
    <Form
      ref={(e) => {
        formRef.current = e;
      }}
      className="w-550px"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      onSubmit={handleSubmit}
      initialValues={{
        storageType: 1,
        storageScale: 1,
        mainNodeMemory: 128,
        slaveNodeMemory: 128,
      }}
    >
      <FormItem field="storageType" label="存储类型" required>
        <Select onChange={handleStorageTypeChange}>
          <Option value={1}>HDFS</Option>
          <Option value={2}>HBase</Option>
          <Option value={3}>MySQL</Option>
        </Select>
      </FormItem>

      <FormItem field="storageScale" label="集群大小" required>
        <Select>
          <Option value={1}>小</Option>
          <Option value={2}>中</Option>
          <Option value={3}>大</Option>
        </Select>
      </FormItem>

      <FormItem field="mainNodeMemory" label="主节点内存(MB)" required>
        <InputNumber min={128} />
      </FormItem>

      {storageType !== 3 && (
        <FormItem field="slaveNodeMemory" label="从节点内存(MB)" required>
          <InputNumber min={128} />
        </FormItem>
      )}

      <FormItem
        wrapperCol={{
          offset: 6,
        }}
      >
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </FormItem>
    </Form>
  );
};

export default NewForm;
